angular.module('Controller')

.controller 'RegisterCtrl', ($scope, $state,cryptUtil,commonUtil,userData,$localStorage,commonConstant,wfAlert,$http) ->
    requestVerificationCode = ->
        $http.post("/verifyCode/#{$scope.data.phone}")
        .success (resp) ->
            if resp.code == 0
                wfAlert.toastInfo "短信验证码已发送"
            else
                wfAlert.toastInfo resp.message
        .error ->
            wfAlert.toastError "您的网络不给力,请检查网络设置"
    activeCountdownButton = ->
        phReg=/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
        if(!phReg.test($scope.data.phone))
            wfAlert.toastInfo '请输入正确的手机号'
            return
        if $scope.countdown == 0
            requestVerificationCode()
            $scope.countdown = 60
            timer = setInterval (->
                $scope.countdown--
                $scope.$apply()
                if $scope.countdown <= 0
                    clearInterval timer
            ), 1000
    _.extend $scope,
        data:
            phone:undefined
            password:undefined
            verifyCode:undefined
        confirm:undefined
        countdown: 0
        getVerificationCode:->
            activeCountdownButton()
        register:->
            if $scope.data.password != $scope.confirm
                wfAlert.toastInfo '两次密码不一样,请重新输入'
                $scope.confirm = undefined
                return
            $scope.data.password = cryptUtil.hex_md5($scope.data.password)
            $http.post("/wechat/member/register/phone",$scope.data)
            .success((resp)->
                console.log resp
                if resp.code==0
                    user=angular.copy resp.message
                    userData.setUser user
                    userData.setToken resp.message.token
                    $state.go 'myself'
                else
                    wfAlert.toastError(resp.message)
            )

